package com.ljph.seckill.common;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.generator.Generator;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

/**
 * Created by yuzhou on 16/7/31.
 */
public class MyGenerator {

    private static final Logger _log = LoggerFactory.getLogger(MyGenerator.class);

    public static DataSource getDataSource() {
        Prop p = PropKit.use("config/mysql.properties", "utf-8");
        C3p0Plugin c3p0Plugin = new C3p0Plugin(p.getProperties());
        c3p0Plugin.start();
        return c3p0Plugin.getDataSource();
    }

    public static void main(String[] args) {
        _log.info("在目录{}下使用代码生成器生成数据实体类：bean和model的结合体", PathKit.getWebRootPath());

        // base model 所使用的包名
        String baseModelPackageName = "com.ljph.seckill.model.base";

        // model 所使用的包名 (MappingKit 默认使用的包名)
        String modelPackageName = "com.ljph.seckill.model";

        // base model 文件保存路径
        String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/com/ljph/seckill/model/base";

        // model 文件保存路径 (MappingKit 与 DataDictionary 文件默认保存路径)
        String modelOutputDir = baseModelOutputDir + "/..";

        _log.info("Base Model Package: {}", baseModelPackageName);
        _log.info("Base Model Output Directory: {}", baseModelOutputDir);
        _log.info("Model Output Directory: {}", modelOutputDir);

        // 创建生成器
        Generator gernerator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir);

        // 设置数据库方言
        gernerator.setDialect(new MysqlDialect());
        // 添加不需要生成的表名
        gernerator.addExcludedTable("adv");
        // 设置是否在 Model 中生成 dao 对象
        gernerator.setGenerateDaoInModel(true);
        // 设置是否生成字典文件
        gernerator.setGenerateDataDictionary(false);
        // 设置需要被移除的表名前缀用于生成modelName。例如表名 "osc_user"，移除前缀 "osc_"后生成的model名为 "User"而非 OscUser
        gernerator.setRemovedTableNamePrefixes("t_");
        // 生成
        gernerator.generate();
    }
}
